package dao;

import application.exceptions.ItemNotFoundException;
import mappings.Appliances;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import utils.HibernateUtil;

import java.util.List;

@SuppressWarnings("JpaQlInspection")
public class AppliancesDao
{
    private static SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

    public List<Appliances> getAllAppliances()
    {
        Session session = sessionFactory.openSession();

        List<Appliances> appliances = session.createCriteria(Appliances.class)
                .list();

        session.close();

        return appliances;
    }

    public Appliances addAppliance(String name)
    {
        Appliances appliance = new Appliances();
        appliance.setName(name);

        org.hibernate.classic.Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();

        session.save(appliance);

        tx.commit();
        session.close();

        return appliance;
    }

    public Appliances editAppliance(Integer id, Appliances appliance) throws ItemNotFoundException
    {
        org.hibernate.classic.Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();

        Appliances applianceToEdit = (Appliances) session.get(Appliances.class, id);

        if(applianceToEdit == null)
        {
            tx.rollback();
            session.close();
            throw new ItemNotFoundException();
        }

        applianceToEdit.setName(appliance.getName());
        session.update(applianceToEdit);
        tx.commit();
        session.close();

        return applianceToEdit;
    }

    public void deleteAppliance(Integer id) throws ItemNotFoundException
    {
        org.hibernate.classic.Session session = sessionFactory.openSession();
        Transaction tx = session.beginTransaction();

        int affectedRows = session.createQuery("delete Appliances where id = :id")
                .setParameter("id", id)
                .executeUpdate();

        if(affectedRows == 0)
        {
            tx.rollback();
            session.close();
            throw new ItemNotFoundException();
        }

        tx.commit();
        session.close();
    }
}
